package com.mydomain.debtbook;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.provider.ContactsContract.Contacts;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class ListNewGroupActivity extends ListActivity {

	protected DebtAdapter myDBAdapter;
	private SimpleCursorAdapter cursorAdapter;
	private Cursor cursor;
	private Button submit;
	private Button back;
	private EditText groupName;
	private OnClickListener myClickListener;
	private ListView listView;
	private ArrayList<String> contactList;
	private boolean isEdit;

	private static final int MY_ERROR_DIALOG_EXIST = 0;
	private static final int MY_ERROR_DIALOG_BLANK = 1;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.new_group);
		myDBAdapter = ((debtBookApplication) this.getApplication())
				.getDatabaseAdapter();
		submit = (Button) findViewById(R.id.ng_submitButton);
		back = (Button) findViewById(R.id.ng_backButton);
		groupName = (EditText) findViewById(R.id.ng_groupEditText);
		contactList = new ArrayList<String>();

		Bundle extras = getIntent().getExtras();
		isEdit = false;
		if (extras != null) {
			groupName.setText(extras.getString("groupName"));
			groupName.setEnabled(false);
			isEdit = true;
		}

		myClickListener = new OnClickListener() {
			@Override
			public void onClick(View v) {

				if (v == submit) {
					if (myDBAdapter.groupExists(groupName.getText().toString())
							&& !isEdit) {

						showDialog(MY_ERROR_DIALOG_EXIST);
					} else if (groupName.getText().toString().equals("")) {
						showDialog(MY_ERROR_DIALOG_BLANK);
					} else {
						submit();
					}
				} else if (v == back) {
					back();
				}

			}
		};

		submit.setOnClickListener(myClickListener);
		back.setOnClickListener(myClickListener);
		cursor = getContacts();
		showContacts(cursor);

		listView = getListView();
		listView.setItemsCanFocus(false);
		listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

	}

	private void submit() {

		Cursor cursor;
		ContentValues groupValues;
		String groupString = groupName.getText().toString();
		SparseBooleanArray selectedItems = listView.getCheckedItemPositions();
		int size = selectedItems.size();
		for (int sbaKey = 0; sbaKey < size; sbaKey++) {

			if (selectedItems.valueAt(sbaKey)) {
				cursor = (Cursor) listView.getItemAtPosition(selectedItems
						.keyAt(sbaKey));

				if ((!myDBAdapter.nameInGroupExists(groupString, cursor
						.getString(cursor
								.getColumnIndexOrThrow(Contacts.DISPLAY_NAME))) && isEdit)
						|| !isEdit)

				{
					groupValues = new ContentValues();
					groupValues.put(DebtAdapter._GROUP, groupString);
					groupValues.put(DebtAdapter._NAME, cursor.getString(cursor
							.getColumnIndexOrThrow(Contacts.DISPLAY_NAME)));

					myDBAdapter.insertGroup(groupValues);
				}

			}

		}

		finish();
	}

	private void back() {
		finish();
	}

	private Cursor getContacts() {
		ContentResolver cr = getContentResolver();
		Cursor myCursor = cr.query(Contacts.CONTENT_URI, new String[] {
				BaseColumns._ID, Contacts.DISPLAY_NAME }, null, null,
				Contacts.DISPLAY_NAME);
		if (myCursor != null) {
			startManagingCursor(myCursor);
		}
		return myCursor;
	}

	private void showContacts(Cursor cursor) {
		cursorAdapter = new SimpleCursorAdapter(this,
				android.R.layout.simple_list_item_multiple_choice, cursor,
				new String[] { Contacts.DISPLAY_NAME },
				new int[] { android.R.id.text1 });
		this.setListAdapter(cursorAdapter);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case MY_ERROR_DIALOG_EXIST:

			return new AlertDialog.Builder(this)
					.setTitle("Error")
					.setMessage("This group name already exists.")
					.setPositiveButton("Ok",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int arg1) {
								}
							}).create();
		case MY_ERROR_DIALOG_BLANK:

			return new AlertDialog.Builder(this)
					.setTitle("Error")
					.setMessage("Please Enter a group name.")
					.setPositiveButton("Ok",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int arg1) {
								}
							}).create();

		}

		return null;
	}

}
